/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blog.city.checkthedep.sessionbeans;

import com.blog.city.checkthedep.entities.RegisteredUser;
import com.blog.city.checkthedep.entities.Article;
import com.blog.city.checkthedep.entities.Category;
import com.blog.city.checkthedep.entities.Comment;
import java.io.File;
import java.io.FileInputStream;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Breath
 */
@Stateless
public class ArticleFacade extends AbstractFacade<Article> implements ArticleFacadeLocal {

    @PersistenceContext(unitName = "com.blog.city_CheckTheDep_war_1.0-SNAPSHOTPU")
    private EntityManager em;

    /**
     * 
     * @return
     */
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    /**
     * 
     * @param em
     */
    protected void setEm(EntityManager em) {
        this.em = em;
    }

    /**
     * 
     */
    public ArticleFacade() {
        super(Article.class);
    }

    /**
     * 
     * @return
     */
    @Override
    public List<Article> latestArticles() {
        List<Article> latestArticles = null;
        if ((List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ORDER BY id DESC").getResultList() != null) {
            latestArticles = (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ORDER BY id DESC").getResultList();
        }
        if (latestArticles.size() >= 10) {
            return (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ORDER BY id DESC").setMaxResults(5).getResultList();
        } else if (latestArticles.size() < 10 && latestArticles.size() >= 5) {
            return (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ORDER BY id DESC").setMaxResults(3).getResultList();
        } else if (latestArticles.size() < 5 && latestArticles.size() >= 3) {
            return (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ORDER BY id DESC").setMaxResults(2).getResultList();
        } else if (latestArticles.size() < 3 && latestArticles.size() >= 1) {
            return (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ORDER BY id DESC").setMaxResults(1).getResultList();
        } else {
            return latestArticles;
        }
    }

    /**
     * 
     * @return
     */
    @Override
    public List<Article> latestPublishedArticlesForTest() {
        List<Article> latestPublishedArticles = null;
        List<Article> latestArticles = null;
        if ((List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ORDER BY id DESC").getResultList() != null) {
            latestArticles = (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ORDER BY id DESC").getResultList();
        }
        for (int i = 0; i < latestArticles.size(); i++) {
            if (latestArticles.get(i).getStatus().equals("published")) {
                latestPublishedArticles.add(latestArticles.get(i));
            }
        }
        if (latestPublishedArticles.size() >= 10) {
            return latestPublishedArticles.subList(0, 5);
        } else if (latestPublishedArticles.size() < 10 && latestPublishedArticles.size() >= 5) {
            return latestPublishedArticles.subList(0, 3);
        } else if (latestPublishedArticles.size() < 5 && latestPublishedArticles.size() >= 3) {
            return latestPublishedArticles.subList(0, 2);
        } else if (latestPublishedArticles.size() < 3 && latestPublishedArticles.size() >= 1) {
            return latestPublishedArticles.subList(0, 1);
        } else {
            return latestPublishedArticles;
        }
    }

    /**
     * 
     * @return
     */
    @Override
    public List<Article> latestPublishedArticles() {
        List<Article> latestPublishedArticles = findArticlesByStatus("published");
        if (latestPublishedArticles.size() >= 10) {
            return latestPublishedArticles.subList(latestPublishedArticles.size()-5, latestPublishedArticles.size());
        } else if (latestPublishedArticles.size() < 10 && latestPublishedArticles.size() >= 5) {
            return latestPublishedArticles.subList(latestPublishedArticles.size()-3, latestPublishedArticles.size());
        } else if (latestPublishedArticles.size() < 5 && latestPublishedArticles.size() >= 3) {
            return latestPublishedArticles.subList(latestPublishedArticles.size()-2, latestPublishedArticles.size());
        } else if (latestPublishedArticles.size() < 3 && latestPublishedArticles.size() >= 1) {
            return latestPublishedArticles.subList(latestPublishedArticles.size()-1, latestPublishedArticles.size());
        } else {
            return latestPublishedArticles;
        }
    }

    /**
     * 
     * @param status
     * @return
     */
    @Override
    public List<Article> findArticlesByStatus(String status) {
        return (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a WHERE a.status=:status").setParameter("status", status).getResultList();
    }

    /**
     * 
     * @param regId
     * @return
     */
    @Override
    public List<Article> findByRegUserId(RegisteredUser regId) {
        return (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a WHERE a.registeredUserId= :registeredUserId").setParameter("registeredUserId", regId).getResultList();
    }
    
    /**
     * 
     * @param regId
     * @return
     */
    @Override
    public List<Article> findByAuthor(RegisteredUser regId) {
        List<Article> usersArticles=findByRegUserId(regId);
        List<Article> publishedArticlesByAuthor=new LinkedList<Article>();
        for(int i=0;i<usersArticles.size();i++){
            if(usersArticles.get(i).getStatus().equalsIgnoreCase("published")){
               publishedArticlesByAuthor.add(usersArticles.get(i));
            }
        }
        return publishedArticlesByAuthor;     
    }
    /**
     * 
     * @param month 
     * @return
     */
    @Override
    public List<Article> findArticleBymonth(Integer month) {
        return (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a WHERE month(a.date)= :date").setParameter("date", month).getResultList();
    }
    
    /**
     * 
     * @param art
     * @return
     */
    @Override
    public List<Category> findCategoryByArticle(Article art) {
        return (List<Category>) getEntityManager().createQuery("SELECT c FROM Article_Has_Category c WHERE c.article_id= :article_id").setParameter("article_id", art).getResultList();
    }
    
    

    /**
     * This method is not used because we had problems with deserializing the object. Could not get back the actual list. The problem was also in
     * Arquillian tests.
     * 
     * @param art
     * @return
     */
    @Override
    public List<Category> findCategoryByArticleNotUsed(Article art) {
        return (List<Category>) art.getCategoryList();
    }

    /**
     * 
     * @return
     */
    @Override
    public List<Article> findAllTestArticles() {
        return (List<Article>) getEntityManager().createQuery("SELECT a FROM Article a ").getResultList();
    }
    
    /**
     * 
     * @param file
     * @param a
     */
    public void saveImage(File file,Article a){
        byte[] bFile = new byte[(int) file.length()];
        try {
	        FileInputStream fileInputStream = new FileInputStream(file);
	        fileInputStream.read(bFile);
	        fileInputStream.close();
                a.setImage(bFile);
        } catch (Exception e) {
	        e.printStackTrace();
        }
    }
    
    
    @Override
    public boolean articleHasComments(Article artId) {
        if (getEntityManager().createQuery("SELECT c FROM Comment c WHERE c.articleId= :articleId").setParameter("articleId", artId).getResultList().size() >0) {
            return true;
        } else {
            return false;
        }
    }
}
